package com.guide.mvc;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.guide.domain.Account;
import com.guide.enums.ErrorCodeEnum;
import com.guide.exception.ServiceException;
import com.guide.service.CommentsService;

public abstract class AbstractController {

	protected static final Logger logger = LoggerFactory.getLogger(AbstractController.class);
	protected static final int ERROR_STATUS = 599;
	protected static final String LOGIN_USER = "loginUser";
	protected static final String LOGIN_DETAL = "loginDetail";
	protected static final String SHOW_WANSHAN = "showWanShan";
	@Autowired 
	protected HttpSession httpSession;
	@Autowired 
	protected CommentsService commentsService;
	
	
	
	protected void refreshUnreadCount() {
		Account account = this.getCurrAccount();
		this.httpSession.removeAttribute("unReadCount");
		this.httpSession.setAttribute("unReadCount", commentsService.getUnreadLetterCount(account.getUserId(), 0));
	}
	protected Account getCurrAccount() {
		Object obj = this.httpSession.getAttribute(LOGIN_USER);
		if(obj==null){
			throw new ServiceException(ErrorCodeEnum.CODE_GUIDE_NO_LOGIN_ERROR);
		}
		return (Account)obj;
	}
	
	@ExceptionHandler
	public @ResponseBody
	Map<String, Object> handleException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

		if (ex == null || ex instanceof TypeMismatchException)
			return null;
		ex.printStackTrace();
		logger.error("exception:", ex);

		response.setStatus(ERROR_STATUS);

		Map<String, Object> model = new HashMap<String, Object>();

		if (ex instanceof ServiceException) {
			ServiceException exception = (ServiceException) ex;

			model.put("error_code", String.valueOf(exception.getErrorCode()));
			model.put("error", exception.getError());
			model.put("error_text", exception.getErrorText());
		} else if (ex instanceof IllegalArgumentException) {
			model.put("error_code", ErrorCodeEnum.SYSTEM_PARAMS_ERROR.getErrorCode());
			model.put("error", ErrorCodeEnum.SYSTEM_PARAMS_ERROR.getError());
			model.put("error_text", ErrorCodeEnum.SYSTEM_PARAMS_ERROR.getErrorText());
		} else {
			model.put("error_code", String.valueOf(ErrorCodeEnum.SYSTEM_ERROR.getErrorCode()));
			model.put("error", ErrorCodeEnum.SYSTEM_ERROR.getError());
			model.put("error_text", ErrorCodeEnum.SYSTEM_ERROR.getErrorText());
		}

		return model;

	}
}
